package com.yuhs.zixing.pay.util;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @className: InetAddress
 * @description: InetAddress
 * @author: xiaofei
 * @create: 2020年01月20日
 */
public final class InetAddress {

    private static final String ANYHOST   = "0.0.0.0";

    private static final String LOCALHOST = "127.0.0.1";

    /**
    * 获取本机IP地址（IPv4）.
    * @return
    */
    public static String getInetAddressString() {
        final java.net.InetAddress address = getInetAddress();
        return address.getHostAddress();
    }

    /**
     * 获取本机合理IP地址.
     * @return
     */
    public static java.net.InetAddress getInetAddress() {
        final Enumeration<NetworkInterface> networkInterfaces = getAllNetworkInterface();
        if (networkInterfaces == null || !networkInterfaces.hasMoreElements()) {
            throw new NetworkException("获取本地网卡失败");
        }

        while (networkInterfaces.hasMoreElements()) {
            final NetworkInterface networkInterface = networkInterfaces.nextElement();
            final Enumeration<java.net.InetAddress> inetAddresses = networkInterface.getInetAddresses();
            if (inetAddresses == null) {
                continue;
            }

            while (inetAddresses.hasMoreElements()) {
                final java.net.InetAddress inetAddress = inetAddresses.nextElement();
                if (isValidAddress(inetAddress)) {
                    return inetAddress;
                }
            }
        }
        throw new NetworkException("获取本机IP地址失败");
    }

    /**
     * 获取本机所有网卡.
     * @return
     */
    private static Enumeration<NetworkInterface> getAllNetworkInterface() {
        Enumeration<NetworkInterface> networkInterfaces;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (final SocketException e) {
            throw new NetworkException("获取本地网卡失败", e);
        }
        return networkInterfaces;
    }

    /**
    * 判断是否为合理的IP地址.
    * @param address
    * @return
    */
    private static boolean isValidAddress(final java.net.InetAddress address) {
        if (address == null || address.isLoopbackAddress()) {
            return false;
        }

        final String name = address.getHostAddress();
        if (name.length() > 16) {
            return false;
        }

        return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name));
    }
}
